import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getUserIdFromRequest } from '@/lib/authUtils'

// Update section order
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
): Promise<NextResponse> {
  try {
    const userId = await getUserIdFromRequest(request)
    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Verify course ownership
    const course = await prisma.vms_course.findFirst({
      where: {
        id: params.id,
        user_id: userId
      }
    })

    if (!course) {
      return NextResponse.json({ error: 'Course not found' }, { status: 404 })
    }

    const body = await request.json()
    const { sections } = body

    if (!sections || !Array.isArray(sections)) {
      return NextResponse.json({ error: 'Invalid sections data' }, { status: 400 })
    }

    // Update each section's order
    const updatePromises = sections.map((section: { id: string; order: number }) =>
      prisma.vms_course_section.update({
        where: {
          id: section.id
        },
        data: {
          order: section.order
        }
      })
    )

    await Promise.all(updatePromises)

    return NextResponse.json({ message: 'Section order updated successfully' })
  } catch (error) {
    console.error('Error updating section order:', error)
    return NextResponse.json(
      { error: 'Failed to update section order' },
      { status: 500 }
    )
  }
}